"""
用户账户相关功能：登录，注销
"""

from django.shortcuts import render, HttpResponse, redirect
from sa.forms.account_form import LoginForm, ChangePasswordForm
from Utils.image_code import check_code
from sa import models
from django.views.decorators.csrf import csrf_exempt
# 导入密码加密
from Utils import encrypt

@csrf_exempt
def user_login(request):
    """ 用户登录 """
    if request.method == "GET":
        form = LoginForm(request)
        context = {
            'form': form,
        }
        return render(request, 'login.html', context=context)
    if request.method == "POST":
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            # 拿到钩子清洁后的数据
            Employee_NO = form.cleaned_data['emp_no']
            Password = form.cleaned_data['pwd']
            print('用户输入的信息：', Employee_NO, Password)
            user_object = models.SA_Info.objects.filter(Employee_No=Employee_NO,
                                                        Password=Password).first()
            if user_object:
                # print(f'当前登录用户是：{user_object.SA_CName}')
                # 登录成功写入 session
                request.session['user_EmpNo'] = user_object.Employee_No
                request.session['user_name'] = user_object.SA_CName
                request.session.set_expiry(60 * 60 * 24 * 2)

                return redirect('index')

            # 因为这里验证不是在钩子中完成。需要在form中为字段增加错误信息，
            # field 将错误信息增加到对应的字段
            form.add_error(field='emp_no', error='用户名或密码错误！')
            form.add_error(field='pwd', error='用户名或密码错误！')
            print(form.errors)
            return render(request, 'login.html', {'form': form})
        else:
            return render(request, 'login.html', {'form': form})


def image_code(request):
    """ 生在图片验证码 """
    # 返回 图片对象 和 要写在图片上的文字
    image_object, code = check_code()
    print(code)
    """ 把图片写入文件 """
    with open('code.png', 'wb') as f:
        image_object.save(f, format='png')

    # 将code 存入session, 以后验证需要
    request.session['image_code'] = code
    request.session.set_expiry(60)

    """ 写图片内容写入内存 stream """
    from io import BytesIO

    stream = BytesIO()  # 创建内存空间
    image_object.save(stream, 'png')
    img = stream.getvalue()  # 获取内存空间的内容

    return HttpResponse(img)


@csrf_exempt
def change_pwd(request):
    """  修改密码 """
    if request.method == "GET":
        form = ChangePasswordForm(request)
    else:
        form = ChangePasswordForm(request, data=request.POST)
        if form.is_valid():
            new_pwd = form.cleaned_data['new_pwd']
            request.sa.Password = encrypt.md5(new_pwd)
            request.sa.save()
            request.session.flush()
            return redirect('user_login')

    context = {
        'form': form,
    }
    return render(request, 'change_pwd.html', context=context)


def user_logout(request):
    # 清空session 清除会话数据并销毁会话 ID。
    # 删除会话ID和所有会话数据，通常还会删除客户端的会话cookie。
    request.session.flush()
    # 仅清除会话数据，保留会话 ID。
    # request.session.clear()
    return redirect('user_login')